$m(function (args) {
    var $this = this.element,
        that = this,
        node = args.node,
        type = args.type;
    ftype = args.fType;
    workSpace = args.workSpace;
    workSpaceId = workSpace ? workSpace.id : null;
    var reg = new RegExp(".png$|.PNG$|.jpg$|.JPG$");
    var max_size = 618;
    var $defaultWorkspaceImg = $('.workspace-default-workspace');

    /**
     * 初始化
     */
    var init = function () {
        if (type == "edit") {
            updateWorkSpaceDialog();
        } else if (type == "uploadCover") {
            upLoadCoverDialog();
        } else {
            createWorkSpaceDialog();
        }
    }

    var upLoadCoverDialog = function () {
        var data = node.workspacenode("getData").args;
        var getData = function () {
            return data;
        }
        $this.dialog({
            resizable: false,
            width: 650,
            height: 300,
            modal: true,
            autoOpen: true,
            title: TempoUtils.locale("bidesign.workspace_uploadcover"),
            close: function () {
                $this.dialog("destroy").remove();
            },
            open: function () {
                $this.find("#fmImg").attr('src', "");
                $this.find("input[name='id']").val(data.ID);
                var form = $this.find("form");
                TempoUtils.parserUi(form, {
                    name: data.NAME
                });
                $this.find(".modifyTime").val(Date.parse(new Date()));
                var url = contextPath + "/images/default_workspace.png";
                if (data.THUMBTIME !== 0) {
                    var time = data.THUMBTIME || data.CREATETIME;
                    url = TempoUtils.securityUrl(contextPath + "/api/ai/workspace/getThumb/" + data.ID + "?time=" + time);
                }
                $this.find("#fmImg").attr('src', url);
                $this.find("input[name=file]").on('change', function (event) {
                    return uploadChange($this, event);
                });
            },
            buttons: [{
                text: TempoUtils.locale("bidesign.workspace_default_cover"),
                click: function () {
                    setDefaultCover($this);
                }
            }, {
                text: TempoUtils.locale("bidesign.workspace_comfirm"),
                click: function () {
                    if ($this.find("#proj_name").hasClass("error"))
                        return;
                    commitUpLoadCover($this);
                }
            }, {
                text: TempoUtils.locale("bidesign.workspace_cancel"),
                click: function () {
                    $this.dialog("close");
                }
            }]
        });
    }

    /**
     * 设置默认封面
     * @param dialog
     */
    var setDefaultCover = function (dialog) {
        var workSpaceId = dialog.find('input[name=id]').val();
        $.ajax({
            url: contextPath + '/api/ai/workspace/cover/update-default',
            data: {
                workSpaceId: workSpaceId
            },
            type: 'post',
            success: function (result) {
                if (result.data) {
                    $("<div/>").alert({
                        msg: TempoUtils.formatText(TempoUtils.locale("bidesign.set_default_workspace")),
                        height: 280
                    });
                    $(node).workspacenode('setImg', contextPath + "/images/default_workspace.png");
                    $(node).workspacenode("getData").args.THUMBTIME = 0;
                    dialog.dialog("close");
                }
            }
        });
    }

    var createWorkSpaceDialog = function () {
        $this.find(".td_nr_font_seperate").button();
        $this.dialog({
            resizable: false,
            width: 620,
            height: 600,
            modal: true,
            autoOpen: true,
            title: TempoUtils.locale("bidesign.workspace_new_WorkSpace"),
            close: function () {
                $this.dialog("destroy").remove();
            },
            open: function () {
                var progress = $("<div/>").tempoprogressbar();
                $.ajax({
                    url: contextPath + '/api/ai/workspace/getMaxIndex',
                    data: {
                        ftype: ftype
                    },
                    type: 'post',
                    success: function (data) {
                        progress.tempoprogressbar("destroy");
                        $this.find("#fmImg").attr('src', contextPath + '/images/default_workspace.png');
                        var form = $this.find("form");
                        TempoUtils.parserUi(form, {
                            name: data
                        });
                        var date = new Date();
                        $this.find('#np_ctime').val(TempoUtils.getNowFormatDate(date));
                        $this.find("#div_new_workspace .createTime").val(Date.parse(date));
                        $this.find("#div_new_workspace .modifyTime").val(Date.parse(date));
                        $this.find("input[name=ftype]").val(ftype);
                        //修改“空间成员”div高度
                        $this.find("#gview_tempo-workspace-permission-grid .ui-jqgrid-bdiv").css("height", "140px");
                        $("#div_new_workspace").css("height", "500px");
                        $this.find("div[name=isDefault]").change(function (name) {
                            $this.find("input[name=isDefault]").val(
                                $(this).checkbox('option').checked ? "true" : "false");
                        })
                        //选择图片按钮事件
                        $this.find("input[name=file]").on('change', function (event) {
                            return uploadChange($this, event);
                        });
                        $this.find("#tempo_reset_btn").bind('click', function (event) {
                            $this.find("#fmImg").attr('src', contextPath + '/images/default_workspace.png');
                            $this.find("input[name=thumb]").val("defaultcover");
                        });
                    }
                })
            },
            buttons: [{
                text: TempoUtils.locale("bidesign.workspace_comfirm"),
                click: function () {
                    if ($this.find("#proj_name").hasClass("error"))
                        return;
                    commitCreateWorkSpace($this);
                }
            }, {
                text: TempoUtils.locale("bidesign.workspace_cancel"),
                click: function () {
                    $this.dialog("close");
                }
            }]
        });
    }

    /**
     * 打开编辑工程的对话框
     */
    var updateWorkSpaceDialog = function () {
        $this.find(".td_nr_font_seperate").button();
        var data = workSpace.args;
        var getData = function () {
            return data;
        }
        $this.dialog({
            resizable: false,
            width: 620,
            height: 600,
            modal: true,
            autoOpen: true,
            title: TempoUtils.locale("bidesign.workspace_edit_WorkSpace"),
            close: function () {
                $this.dialog("destroy").remove();
            },
            open: function () {
                $this.find("#fmImg").attr('src', "");
                $this.find("input[name='id']").val(data.ID);
                var form = $this.find("form");
                if (data.WORK_SPACE_TYPE == "self") {
                    form.find(".tempo_workspace_invitusergrid").hide();
                    form.find(".tempo_workspace_entername").hide();
                    $this.dialog({height: 300})
                } else {
                    form.find(".tempo_workspace_invitusergrid").show();
                    $this.dialog({height: 600})
                }
                TempoUtils.parserUi(form, {
                    name: data.NAME,
                    descr: data.DESCR,
                    ftype: ftype
                });
                $this.find("input[name=ftype]").val(ftype);
                $this.find("div[name=isDefault]").change(function (name) {
                    $this.find("input[name=isDefault]").val(
                        $(this).checkbox('option').checked ? "true" : "false");
                })
                if (workSpace.isDefault == "true") {
                    $this.find("div[name=isDefault]").checkbox("check", "true", true);
                }
                $this.find(".modifyTime").val(Date.parse(new Date()));
                var url = contextPath + "/images/default_workspace.png";
                if (data.THUMBTIME !== 0) {
                    var time = data.THUMBTIME || data.CREATETIME;
                    url = TempoUtils.securityUrl(contextPath + "/api/ai/workspace/getThumb/" + data.ID + "?time=" + time);
                }
                $this.find("#fmImg").attr('src', url);
                $this.find("input[name=file]").on('change', function (event) {
                    return uploadChange($this, event);
                });
                $this.find("#tempo_reset_btn").bind('click', function (event) {
                    $this.find("#fmImg").attr('src', contextPath + '/images/default_workspace.png');
                    $this.find("input[name=thumb]").val("defaultcover");
                    $this.find("input[name=file]").val("").removeAttr("used");
                });
            },
            buttons: [{
                text: TempoUtils.locale("bidesign.workspace_comfirm"),
                click: function () {
                    if ($this.find("#proj_name").hasClass("error"))
                        return;
                    commitUpdateWorkSpace(node, $this);
                }
            }, {
                text: TempoUtils.locale("bidesign.workspace_cancel"),
                click: function () {
                    //保存用户权限信息
                    var grid = $this.find("#tempo-workspace-permission-grid");
                    var data = grid.datagrid('getRowData');
                    var userNum = data.length + 1;
                    node.find(".content-button-userNum").text(userNum);
                    $(node).workspacenode("setUserNum", userNum);
                    $this.dialog("close");
                }
            }]
        });
    }


    /**
     * 提交封面
     */
    var commitUpLoadCover = function (dialog) {
        var form = dialog.find("form");
        var dataJson = TempoUtils.getRecord(form);
        var form = $("<form id='tempo-workspace-save-form'/>").appendTo($("body"));
        form.attr("action", contextPath + ('/api/ai/workspace/uploadCover'));
        form.attr("method", "post");
        form.attr("enctype", "multipart/form-data");
        var pInput = $("<input name='workspace'/>");
        pInput.appendTo(form);
        pInput.val(JSON.stringify(dataJson));
        pInput.hide();
        var picBtns = dialog.find("#zhe_ge_id_yong_yu_jiang_wen_jian_shang_chuan_an_niu_fang_hui").find('input[name=file]');
        if (picBtns.length == 0) {
            dialog.find("form").find('#btnPickPic0').appendTo(form);
            if (dialog.find("form").find('#btnPickPic0').val().length == 0) {
                $("<div/>").alert({msg: TempoUtils.locale("bidesign.workspace_uploadcover_empty")});
                form.remove();
                return;
            }
        } else {
            if (picBtns.val().length == 0) {
                $("<div/>").alert({msg: TempoUtils.locale("bidesign.workspace_uploadcover_empty")});
                form.remove();
                return;
            } else {
                picBtns.appendTo(form);
                picBtns.hide();
            }

        }
        picBtns.hide();
        var progress = $("<div/>").tempoprogressbar();
        form.ajaxSubmit({
            dataType: 'json',
            beforeSubmit: function (result) {
                return true;
            },
            success: function (obj) {
                form.remove();
                progress.tempoprogressbar("destroy");
                if (obj.msg) {
                    $("<div/>").alert({msg: TempoUtils.locale(obj.msg)});
                } else {
                    var url = contextPath + "/images/default_workspace.png";
                    if (obj.THUMBTIME !== 0) {
                        var time = obj.THUMBTIME || obj.CREATETIME;
                        url = TempoUtils.securityUrl(contextPath + "/api/ai/workspace/getThumb/" + obj.ID + "?time=" + time);
                    }

                    var data = {
                        id: obj.ID,
                        thumb: url,
                        name: obj.NAME,
                        userNum: obj.USERNUM,
                        appNum: obj.APPNUM,
                        args: obj,
                        isDefault: obj.IS_DEFAULT,
                        showTitle: false,
                        isSelf: obj.WORK_SPACE_TYPE == "self"
                    };
                    $(node).workspacenode("option", "data", data);
                    $(node).workspacenode('setImg', url);
                    dialog.dialog("close");
                }
            },
            complete: function () {
                picBtns.appendTo($("#zhe_ge_id_yong_yu_jiang_wen_jian_shang_chuan_an_niu_fang_hui"));
                picBtns.unbind('change').bind('change', function (event) {
                    return uploadChange($this, event);
                });
            }
        });
    }

    /**
     * 提交新建工程
     */
    var commitCreateWorkSpace = function (dialog) {
        var form = dialog.find("form");
        var id = form.find("input[name='id']");
        id.val(workSpaceId);
        if (!form.formValidate()) {
            return;
        }
        var dataJson = TempoUtils.getRecord(form);
        if (dataJson.name.trim() == "") {
            $("<div/>").alert({msg: TempoUtils.locale("bidesign.workspace_name_empty")});//名称为空，请重新填写！
            return;
        }
        if (dataJson.name.trim().length > 60) {
            $("<div/>").alert({msg: TempoUtils.formatText(TempoUtils.locale("bidesign.workspace_name_length"), 60)});//名称过长，请重新填写！
            return;
        }
        if (dataJson.descr && dataJson.descr.trim().length > 255) {
            $("<div/>").alert({msg: TempoUtils.locale("bidesign.workspace_description_length")});
            return;
        }
        var form = $("<form id='tempo-workspace-save-form'/>").appendTo($("body"));
        form.attr("action", contextPath + ('/api/ai/workspace/workSpaceCreatePost'));
        form.attr("method", "post");
        form.attr("enctype", "multipart/form-data");
        var pInput = $("<input name='workspace'/>");
        pInput.val(JSON.stringify(dataJson));
        pInput.appendTo(form);
        var picBtns = dialog.find("#zhe_ge_id_yong_yu_jiang_wen_jian_shang_chuan_an_niu_fang_hui").find('input[name=file]');
        if (picBtns.length == 0) {
            dialog.find("form").find('#btnPickPic0').appendTo(form);
        } else {
            picBtns.appendTo(form);
            picBtns.hide();
        }
        var progress = $("<div/>").tempoprogressbar();
        form.ajaxSubmit({
            dataType: 'json',
            beforeSubmit: function (result) {
                return true;
            },
            success: function (obj) {
                progress.tempoprogressbar("destroy");
                form.remove();
                if (obj != null) {
                    if (obj.message != null && obj.message) {
                        $("<div/>").alert({msg: TempoUtils.locale(obj.message)});
                        return;
                    }
                    var grid = dialog.find("#tempo-workspace-permission-grid");
                    var data = grid.datagrid('getRowData');
                    if (data && data.length > 0) {
                        var ids = [];
                        var types = [];
                        for (var i = 0; i < data.length; i++) {
                            ids.push(data[i].ID);
                            types.push($('input[name=' + data[i].TYPE.substr(data[i].TYPE.indexOf("name=") + 6, 36) + ']:first').is(":checked") ? "2" : "1");
                        }
                        $.ajax({
                            url: contextPath + "/api/ai/workspace/privis-type/create",
                            method: 'POST',
                            async: false,
                            data: {
                                ids: ids.join(','),
                                types: types.join(','),
                                workSpaceId: obj.data
                            },
                            success: function (data) {
                                dialog.dialog("close");
                            }
                        })
                    } else {
                        dialog.dialog("close");
                    }
                }
                var workSpaceId = obj.data;
                //此处增加校验，处理安全测试60419 tempo AI创建工作站处XSS
                workSpaceId = checkworkSpaceId(workSpaceId)
                var thisUrl = contextPath + "/api/" + (ftype == "mining" ? "ai" : "bi") + "/resource/view/theme?workSpaceId=" + workSpaceId;
                thisUrl = TempoUtils.addHideIconParam(thisUrl);
                window.location.href = thisUrl;
            },
            complete: function () {
                picBtns.appendTo($("#zhe_ge_id_yong_yu_jiang_wen_jian_shang_chuan_an_niu_fang_hui"));
                picBtns.unbind('change').bind('change', function (event) {
                    return uploadChange($this, event);
                });
            }
        });
    }

    var checkworkSpaceId = function (params) {
        var regExp = new RegExp(/^[0-9a-zA-z]*$/);
        var workSpaceId = params.toString()
        if (regExp.test(workSpaceId)) {
            return workSpaceId;
        } else {
            return "";
        }
    }


    /**
     * 提交编辑操作
     */
    var commitUpdateWorkSpace = function (node, dialog) {
        var form = dialog.find("form");
        if (!form.formValidate()) {
            return;
        }
        var dataJson = TempoUtils.getRecord(form);
        if (dataJson.name && dataJson.name.trim().length > 60) {
            $("<div/>").alert({msg: TempoUtils.formatText(TempoUtils.locale("bidesign.workspace_tooptip_name_length"), 60)});//工程名过长
            return;
        }
        if (dataJson.descr && dataJson.descr.trim().length > 255) {
            $("<div/>").alert({msg: TempoUtils.locale("bidesign.workspace_description_length")});
            return;
        }
        var form = $("<form/>").appendTo($("body"));
        form.attr("action", contextPath + ('/api/ai/workspace/workSpaceUpdatePost'));
        form.attr("method", "post");
        form.attr("enctype", "multipart/form-data");
        var pInput = $("<input name='workspace'/>");
        pInput.val(JSON.stringify(dataJson));
        pInput.appendTo(form);
        pInput.hide();
        var picBtns = dialog.find("#zhe_ge_id_yong_yu_jiang_wen_jian_shang_chuan_an_niu_fang_hui").find('input[name=file]');
        if (picBtns.length == 0) {
            dialog.find("form").find('#btnPickPic0').appendTo(form);
        } else {
            picBtns.appendTo(form);
            picBtns.hide();
        }
        var progress = $("<div/>").tempoprogressbar();
        form.ajaxSubmit({
            dataType: 'json',
            beforeSubmit: function (result) {
                return true;
            },
            success: function (result) {
                form.remove();
                obj = result.data;
                progress.tempoprogressbar("destroy");
                if (!result.success) {
                    if (result.message) {
                        $("<div/>").alert({msg: TempoUtils.locale(result.message)});
                    }
                } else {
                    var url = contextPath + "/images/default_workspace.png";
                    if (obj.THUMBTIME !== 0) {
                        var time = obj.THUMBTIME || obj.CREATETIME;
                        url = contextPath + "/api/ai/workspace/getThumb/" + obj.ID + "?time=" + time;
                    }
                    var data = {
                        id: obj.ID,
                        thumb: url,
                        name: obj.NAME,
                        userNum: obj.USERNUM,
                        appNum: obj.APPNUM,
                        args: obj,
                        isDefault: obj.IS_DEFAULT,
                        showTitle: false,
                        isSelf: obj.WORK_SPACE_TYPE == "self",
                        descr: obj.DESCR
                    };
                    //是否进行编辑了默认空间
                    var changeDefault = $(node).workspacenode("option", "data").isDefault != obj.IS_DEFAULT;
                    $(node).workspacenode("option", "data", data);
                    $(node).workspacenode('setImg', url);
                    $(node).workspacenode('setText', obj.NAME);
                    node.find("span.tempo-icon-item-span-text").attr('title', obj.NAME);
                    if (changeDefault) {
                        if (obj.IS_DEFAULT == "true") {
                            $(".tempo-workspacenode").each(function () {
                                $(this).workspacenode("setDefaultspace", "false");
                            });
                            $(node).workspacenode("setDefaultspace", obj.IS_DEFAULT);
                            $defaultWorkspaceImg.css({
                                top: -186,
                            }).show().appendTo(node);
                        } else {
                            $defaultWorkspaceImg.hide();
                        }
                    }
                    //保存用户权限信息
                    var grid = dialog.find("#tempo-workspace-permission-grid");
                    var data = grid.datagrid('getRowData');
                    var userNum = data.length + 1;
                    node.find(".content-button-userNum").text(userNum);
                    $(node).workspacenode("setUserNum", userNum);
                    if (data && data.length > 0) {
                        var ids = [], types = [];
                        for (var i = 0; i < data.length; i++) {
                            ids.push(data[i].ID);
                            types.push($('input[name=' + data[i].TYPE.substr(data[i].TYPE.indexOf("name=") + 6, 36) + ']:first').is(":checked") ? "2" : "1");
                        }
                        $.ajax({
                            url: contextPath + "/api/ai/workspace/privis/update",
                            method: 'POST',
                            data: {
                                ids: ids.join(','),
                                types: types.join(','),
                                workSpaceId: workSpaceId
                            },
                            success: function (data) {
                                dialog.dialog("close");
                            }
                        });
                    } else {
                        dialog.dialog("close");
                    }
                }
            },
            complete: function () {
                picBtns.appendTo($("#zhe_ge_id_yong_yu_jiang_wen_jian_shang_chuan_an_niu_fang_hui"));
                picBtns.unbind('change').bind('change', function (event) {
                    return uploadChange($this, event);
                });
            }
        });
    }

    /**
     * 图片切换
     * @param dialog
     * @param event
     * @returns {boolean}
     */
    var uploadChange = function (dialog, event) {
        var btn = $(event.target);
        //是否选择成功
        var success = true;
        if (btn[0].files && btn[0].files.length > 0) {
            //IE10 Chrom Firefox
            var size = btn[0].files[0].size / 1024;
            if (!reg.test(btn[0].files[0].name)) {
                $("<div/>").alert({
                    title: TempoUtils.locale("bidesign.workspace_base_tooltip"),
                    msg: TempoUtils.locale("bidesign.workspace_picture_format_tip")
                });
                success = false;
            } else if (size > max_size) {
                $("<div/>").alert({
                    title: TempoUtils.locale("bidesign.workspace_base_tooltip"),
                    msg: TempoUtils.replaceArray(TempoUtils.locale("bidesign.workspace_picture_size_not"), max_size)
                });
                success = false;
            } else if (size == 0) {
                $("<div/>").alert({
                    title: TempoUtils.locale("bidesign.workspace_base_tooltip"),
                    msg: TempoUtils.replaceArray(TempoUtils.locale("bidesign.workspace_picture_0_size_exceed"), max_size)
                });
                success = false;
            } else {
                var url = window.URL.createObjectURL(btn[0].files[0]);
                if (url) {
                    dialog.find("#fmImg").attr('src', url);
                }
                success = true;
            }
            if (success == true) {
                //如果选择成功，将当前组件按钮作为结果文件，并将备用按钮切换为可用按钮
                //标记当前按钮为结果可使用状态，并隐藏
                btn.attr("used", "true");
                //这一行也注掉了，有问题同样可以放开
//				btn.attr("used", "true").closest(".tempo-upload-text-label").css("display", "none");
                //将除当前按钮外的按钮内容清空并显示，用于下次选择
//				dialog.find("input[name=file]").not(btn).val("").removeAttr("used").closest(".tempo-upload-text-label").css("display", "");
                $this.find("input[name=thumb]").val("");
            } else {
                //如果选择失败，将当前组件选择清空，供重新选择
                btn.val("").removeAttr("used");
            }
        }
        return success;
    }

    !function () {
        init();
        //修改“空间成员”div高度
        $("#gview_tempo-workspace-permission-grid .ui-jqgrid-bdiv").css("height", "140px");
        $("#div_new_workspace").css("height", "500px");
    }();
}); 